// Copyright (C) 2006 Taylor L. Riché <riche@cs.utexas.edu>
//  
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software 
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//

#include "MutatingQueue.hh"
#include "Function.hh"
#include "PCon.hh"

using namespace lee;

PCon * 
MutatingQueue::pop() 
{
  // remove work from map entry and total
  PCon * pcon = coreQueue.pop();
  Function * func = pcon->getFunction();
  uint32_t funcWork = func->getWork();
  reduceWork(func, funcWork);
  return pcon;
}

PCon *
MutatingQueue::peek()
{
  // this won't do anything with work
  return coreQueue.peek();
}

bool
MutatingQueue::push(PCon * pcon) 
{
  // check to see if current pcon violates guarantee
  // if it does, tell function to ask for more resources
  // enqueue packet and add work to map
  bool success = true;
  Function * func = pcon->getFunction();
  uint32_t funcWork = func->getWork();
  if(addWork(func, funcWork)) {
    coreQueue.push(pcon);
  }
  else {
    success = false;
  }
  return success;
}

void
MutatingQueue::forcePush(PCon * pcon)
{
  coreQueue.push(pcon);
  return;
}

void
MutatingQueue::reduceWork(Function * func, uint32_t work)
{
  Synchronized::Scope mutex(this);
  totalWork -= work;
  assert(totalWork >= 0);
  workMap[func] -= work;
  return;
}

bool
MutatingQueue::addWork(Function * func, uint32_t work)
{
  Synchronized::Scope mutex(this);
  bool success = true;
  totalWork += work;
  workMap[func] += work;
  if(totalWork > workThreshold) {
    success = false;
  }
  return success;
}
